#include "logwriter.h"

#include <string>
#include <fstream>
#include "subject.h"
#include "loghandler.h"


using spacedefender::Loghandler;
using spacedefender::LogWriter;
using spacedefender::Subject;

LogWriter::LogWriter(std::string fileName) 
{
	Init(fileName, true);
}

LogWriter::LogWriter(std::string fileName, bool clearFile)
{
	Init(fileName, clearFile);
}

void LogWriter::Init(std::string fileName, bool clearFile)
{
	_fileName = fileName;
	
	if(clearFile)
	{
		_logFile.open(_fileName.c_str(), std::ios::trunc);
	}
	else
	{
		_logFile.open(_fileName.c_str(), std::ios::app);
	}
	
	Loghandler::GetInstance()->Attach(this);
}

LogWriter::~LogWriter()
{
	Loghandler::GetInstance()->Detach(this);
	
	if(_logFile.is_open())
	{
		_logFile.close();
	}
}

void LogWriter::Notification(const Subject* sender)
{
	if(Loghandler::GetInstance() == sender)
	{
		_logFile << Loghandler::GetInstance()->GetLatestLogText() << std::endl;
	}
}